home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Turnbull China Bikeride
/
Turnbull China Bikeride - Disc 2.iso
/
ACORNUSERS
/
EMULATOR
/
EMUL6502
/
Sources
/
Factorial
< prev
next >
Wrap
Text File
|
1998-08-27
|
2KB
|
70 lines
;Alain BROBECKER (aka baah/Arm's Tech), 27aug1998
;
;Computes 8!=40320 by using recursive calls. If the result is wrong, it jumps
;at adress 0 (should contain &00='brk'), else it ends with the 'brk' inside
;the code (and you can relax =).
#name FactorialX
#list
#base &100-4 ;Start assembly here
#rw &100 ;Load adress
#rw &100 ;Exec adress
;Zero page adresses used as storage
#set fact = &10
#set mul1 = &12
#set mul2 = &13
ldx #&ff ;Initialise stack
txs
ldx #0 ;Initialise z,fact to 7
stx z,fact+1
ldx #8
stx z,fact
jsr factorial ;Recursive call with x=7
lda #&80 ;Compare result with 40320=&9d80
cmp z,fact
beq no_error
.error
jmp 0
.no_error
lda #&9d
cmp z,fact+1
bne error
brk
;Multiply z,fact with (x-1) and call himself if x-1>1
.factorial
dex
cpx #1
beq factorial_end
stx z,mul1 ;mul1=x
lda z,fact ;mul2=fact
sta z,mul2
lda z,fact+1
sta z,mul2+1
lda #0 ;fact=0 will contain mul2*mul1
sta z,fact
sta z,fact+1
ldy #8 ;Nb of shift to perform
.shiftmul_one
lsr z,mul1 ;Carry = shifted bit
bcc next_shift
clc ;Perform fact+=mul2
lda z,mul2 ;16 bits addition
adc z,fact
sta z,fact
lda z,mul2+1
adc z,fact+1
sta z,fact+1
;Rotate word in mul2
.next_shift
asl z,mul2 ;Shift word
rol z,mul2+1
dey:bne shiftmul_one
jsr factorial ;Recursive call
.factorial_end
rts